<?php
    if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();}
?>
<script src="js/jquery.flot.js"></script>
<div id="stockwidget" class="widgetcontainer">
    <div id="stockheading" class="widgetheading">
        Stock Lookup<img src="images/plus.jpg"/>
    </div>
    <div id="stock" class="widget">
        <script type="text/javascript">
            $("#stockheading").data("divlink", $("#stock"));
            $("#stock").data("heading", $("#stockheading"));
            $("#stockheading").data("clear", function() {
                //Clear the data on user logout
                $("#stocksearch").val("");
                $("#stock_current_val_table tbody > tr").remove();
            });
        </script>
        <div id="clear"></div>
        <div >
            <form>
                Stock Search: <input id="stocksearch" style="margin-left:10px;margin-right:30px;width:200px;" name="stocksearch" type="text" />
                <input type="submit" class="button blue" value="Lookup" onclick="doStockLookup($('#stocksearch').val());return false;"/>
            </form>
            <div>
                <br/>
                <b>Click on a stock to view its share price history.</b>
                <table id="stock_current_val_table" class="rounded-corner sortable">
                    <thead style="text-align:center;"><tr>
                        <th>Stock Symbol</th><th>Stock Description</th><th>Share Price</th><th>Volume</th>
                    </tr></thead>
                    <tbody id="stock_current_val_table_body">
                    </tbody>
                </table>
                
                <hr />
                <br />
                <center><h3 id="graph_title"></h3></center>
                <div id="graph_div_new" style="width:800px;height:325px;margin:auto;"></div>
<!--                <h3 style="margin:0px"><b><div id="slider_div_label_new"></div></b></h3>
                <div id="slider_div_toolbar" style="width:100%;">
                    <table>
                        <tr>
                            <td><input id="min_slider_button" type="button" value="Min" style="height:35px;"/></td>
                            <td style="width:10px"></td>
                            <td><div id="slider_div_new" style="width:400px;"></div></td>
                            <td style="width:10px"></td>
                            <td><input id="max_slider_button" type="button" value="Max" style="height:35px;"/></td>
                        </tr>
                    </table>
                </div>-->
                <br/>
            </div>
        </div>
        
    </div>
    <br />
</div>
<script type="text/javascript">
    
    $("#stocksearch").autocomplete({
        delay: 100,
        highlight: true,
        source: 'backend/suggestion.php',
        search: function () {
            var term = extractLast(this.value);
            if (term.length < 1) return false;
        },
        focus: function () {
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
            terms.pop();
            terms.push(ui.item.value);
            terms.push("");
            this.value = terms.join(", ");
            return false;
        },
        source: function (request, response) {
            $.getJSON("../backend/autosuggest.php", {
                term: extractLast(request.term)
            }, response);
        }
    });
    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }    
    function doStockLookup(terms) {
        if (terms == "") {
            $("#stock_current_val_table tbody > tr").remove();
            var tr = $("<tr>");
            tr.append($("<td colspan='4'>").text("Please enter some stocks to lookup!"));
            $("#stock_current_val_table_body").append(tr);
            return;
        }
        $.ajax({
            type: 'POST',
            url: '../backend/stock_lookup.php',
            dataType: 'json',
            data: {
                stocks: terms
            },
            success: function(data) {
                $("#stock_current_val_table tbody > tr").remove();
                var any = false;
                $.each(data, function(key, value) {
                    any = true;
                    var tr = $("<tr>");
                    tr.bind("click", function() {
                        var stockSym = $($(this).find("td")[0]).text();
                        displayStockHistory(stockSym);
                    });
                    tr.append($("<td>").text(key));
                    tr.append($("<td>").text(value["StockName"]));
                    tr.append($("<td style='text-align:right;'>").text(priceFormat(value["SharePrice"])));
                    tr.append($("<td style='text-align:right;'>").text(value["Shares"]));
                    $("#stock_current_val_table_body").append(tr);
                });
                if (!any) {
                    var tr = $("<tr>");
                    tr.append($("<td colspan='4'>").text("No stocks found!"));
                    $("#stock_current_val_table_body").append(tr);
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
    function showTooltip(x, y, contents) {        
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80,
            'z-index': 5
        }).appendTo("body").fadeIn(50);
    }
    lastHover = null;
    function displayStockHistory(StockSymbol) {
        $.ajax({
            type: 'POST',
            url: '../backend/stock_history.php',
            dataType: 'json',
            data: {
                stocks: StockSymbol
            },
            success: function(stockhist) {
                $("#graph_title").text(StockSymbol);
                var options = {
                    grid: { hoverable: true },
                    series: {
                        lines: { show: true },
                        points: { show: true }
                    },
                    xaxis: {
                        mode: "time",
                        timeformat: "%y-%m-%d %H:%M:%S"
                    }
                };
                var price = [];
                var volume = [];
                $.each(stockhist, function(key, value) {
                    $.each(value, function(index, stockhistory) {
                        var share = [stockhistory["Time"], stockhistory["SharePrice"] / 100.0];
                        price.push(share);
                        //var share = [stockhistory["Time"], stockhistory["Volume"]];
                    });
                    return false;
                });
                var plot = $.plot($("#graph_div_new"), 
                [
                    //[ [1, 3], [2, 14.01], [3.5, 3.14] ]
                    //[ ["2010-11-01 00:00:00", 3], ["2010-11-02 00:00:00", 14.01], ["2010-11-03 00:00:00", 3.14] ]
                    
                     //   {label: "Price", data: [["1250827200000", 3], ["1251086400000", 14.01], ["1251172800000", 3.14]] },
                     //   {label: "Price2", data: [["1250827200000", 7], ["1251086400000", 17.01], ["1251172800000", 7.14]] }
                    
                    { label: StockSymbol + " Share Price", data: price }
                    //, { label: "Volume", data: }
                ], options);
                $("#graph_div_new").unbind(); //Unbind previous handler
                $("#graph_div_new").bind("plothover", function (event, pos, item) {
                    if (lastHover != null && item && lastHover.datapoint[0] == item.datapoint[0]) return;
                    $("#tooltip").remove(); plot.unhighlight();
                    if (item) {
                        var series = plot.getData();
                        var date = new Date(item.datapoint[0]);
                        
                        var tooltip_html = /*item.datapoint[0]*/date.toLocaleString() + "<table>";
                        var x = item.datapoint[0];
                        for (var i = 0; i < series.length; i++) {
                            var datapoint = find(x, series[i].data);
                            if (datapoint != null) {
                                    plot.highlight(series[i], datapoint);
                                    var y = datapoint[1];
                                    if (series[i] == item.series) {
                                        tooltip_html += "<tr><td>\u2022&nbsp;<b>" + series[i].label + "</b></td><td><b>" + y + "</b></td></tr>"; 
                                    } else {
                                        tooltip_html += "<tr><td>" + series[i].label + "</td><td>" + y + "</td></tr>";
                                    }
                            }
                        }
                        tooltip_html += "</table>";
                        showTooltip(item.pageX, item.pageY, tooltip_html);
                        lastHover = item;
                    } else {
                        lastHover = null;
                    }
                });
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
    
    function find(year, data) {
        var ret = null;
        $.each(data, function(index, yeardata) {
            if (yeardata[0] == year) {
                ret = yeardata;
                return false;
            }
            return true;
        });
        return ret;
    }
</script>